﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataLayer
{
    internal class DBConnect : IDBConnect
    {
        public string GetConnectionString()
        {
            return System.Configuration.ConfigurationManager.ConnectionStrings["onetouch"].ConnectionString;
        }

        private SqlConnection Getconnection()
        {
            SqlConnection con = new SqlConnection(GetConnectionString());
            if (con.State != ConnectionState.Open)
                con.Open();
            return con;
        }

        public int Execute(string query)
        {
            int chk = 0;
            try
            {
                SqlConnection con = Getconnection();
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    chk = cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                Helper.ErrorLogger.Log(ex.Message);
                throw;
            }
            return chk;
        }

        public DataTable Read(string query)
        {
            DataTable dt = new DataTable();
            try
            {
                SqlConnection con = Getconnection();
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows)
                        dt.Load(dr);
                }
            }
            catch (Exception ex)
            {
                Helper.ErrorLogger.Log(ex.Message);
                throw;
            }
            return dt;
        }

        public string ReadScalar(string query)
        {
            string item;
            try
            {
                SqlConnection con = Getconnection();
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    item = string.Format("{0}", cmd.ExecuteScalar());

                }
            }
            catch (Exception ex)
            {
                Helper.ErrorLogger.Log(ex.Message);
                throw;
            }
            return item;
        }
    }
}
